package com.example.wangning.mycarofcountry.forum.lecturer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.example.mycarofcountry.entity.dao.Forum_total;
import com.example.wangning.mycarofcountry.R;
import com.example.wangning.mycarofcountry.cache.VolleySingleton;
import com.example.wangning.mycarofcountry.db.DaoHelper;
import com.example.wangning.mycarofcountry.tool.DividerGridItemDecoration;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/14.
 */
public class LecturerFragment extends Fragment {
    private VolleySingleton volleySingleton;
    private RecyclerView lectureView;
    private LecturerAdapter lecturerAdapter;
    private SwipeRefreshLayout hotData_Swipe;
    private TextView hotData_Tv;
    private DaoHelper helper;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_total,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lectureView = (RecyclerView) view.findViewById(R.id.lectureView);
        hotData_Swipe = (SwipeRefreshLayout) view.findViewById(R.id.hotData_Swipe);
        hotData_Tv = (TextView) view.findViewById(R.id.hotData_Tv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lecturerAdapter = new LecturerAdapter(getActivity());
        lectureView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lectureView.addItemDecoration(new DividerGridItemDecoration(getActivity()));
        lectureView.setAdapter(lecturerAdapter);
        helper = DaoHelper.getInstance();
        getStringRequest();
        setrefresh();
    }
    private void setrefresh() {
        //设置刷新时动画的颜色，可以设置4个
        hotData_Swipe.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        hotData_Swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                hotData_Tv.setVisibility(View.VISIBLE);
                hotData_Tv.setText("正在刷新");
                getStringRequest();
            }
        });
    }
    private void getStringRequest() {
        volleySingleton = VolleySingleton.getVolleyIntance();
        String url = "http://app.api.autohome.com.cn/autov5.0.0/Club/shotfoumlist-pm1-p1-s50.json";
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                TotalBean totalBean = gson.fromJson(response,TotalBean.class);
                if (totalBean != null){
                    TotalResult totalResult = totalBean.getResult();
                    List<Forum_total> totallists = totalResult.getList();
                    if (totallists != null && totallists.size() > 0){
                        lecturerAdapter.addData(totallists);
                        helper.addTotal(totallists);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hotData_Tv.setText("");
                                hotData_Tv.setVisibility(View.GONE);
                            }
                        }, 1000);
                        hotData_Swipe.setRefreshing(false);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                lecturerAdapter.addData(helper.seacherTotal());
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        volleySingleton.addRequest(stringRequest);

    }
}
